/**
 * Created by 叶子 on 2017/7/30.
 * http通用工具函数
 */
const axios = require('axios');
// const NProgress = require('nprogress');
// require('nprogress/nprogress.css')
// import { history } from '@/index.js';
const Qs = require('qs');
// import { Feedback } from '@icedesign/base';
var FormDataOfNode = require('form-data');
// const Toast = Feedback.toast;

const RELEASE_URL = '';
// export const DEBUG_URL = 'http://www.chehangjia.cn:8080';
const DEBUG_URL = '';
// const DEBUG_URL = 'http://192.168.0.61:8091';
const DEF_DIR = '';
// export const OLD_DIR = '/guinong_web';

const MOCK_URL = 'http://localhost:4444';
// export const baseUrl = DEBUG_URL;

// axios.defaults.baseURL = baseUrl;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

function progressStart() {
  // NProgress.start();
}

function progressDone() {
  // NProgress.done();
}

/* between 0..1. */
function progressSet(progress) {
  // NProgress.set(progress);
}

/*
 http请求统一实现
 get : params 是object对象
 post : FormData对象
 */
const request = (requestData, headerParams = {}) => {
  let isOk = false;
  const { url: url = '', method: method = 'get', dir = DEF_DIR, env = 'browser' } = requestData;

  let reqUrl = /^http/.test(url) ? url : DEBUG_URL + dir + url;
  // console.log(reqUrl)
  let { params, body } = requestData;
  let headers = {};
  if (method === 'put') {
    if (params) {
      headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
    }
    if (body) {
      headers = { 'Content-Type': 'application/json' };
    }
  }
  if (method === 'post') {
    if (params ) {
      let format = null;
      if (env !== 'browser') {
          format = new FormDataOfNode();
      } else {
          format = new FormData();
      }
      console.log(format)
      for (const temp in params) {
          const val = params[temp];
          if (val instanceof Array) {
              val.forEach((item) => {
                  format.append(temp, item);
              });
          } else {
              format.append(temp, val);
          }
      }

      headers = { 'Content-Type': 'form-data' };
      params = null;
      body = format;
      console.log(body)
    }
  }
  headers = { ...headerParams, ...headers };
  const http = axios.request({
    url: reqUrl,
    method,
    params,
    data: body,
    headers,
    paramsSerializer(tempPrams) {
      return Qs.stringify(tempPrams, { arrayFormat: 'repeat' });
    },
    // `onUploadProgress` 允许为上传处理进度事件
    onUploadProgress(progressEvent) {
      // 对原生进度事件的处理
      const { loaded, total } = progressEvent;
      progressSet(loaded / total);
    },

    // `onDownloadProgress` 允许为下载处理进度事件
    onDownloadProgress(progressEvent) {
      // 对原生进度事件的处理
    },
  });
  progressStart();
  return new Promise((resolve, reject) => {
    http.then((response) => {
      if (response.status === 200) {
        isOk = true;
      }
      return response.data;
    })
      .then(data => {
        if (isOk) {
          if (requestData.skipCheckResp) {
            resolve(data);
          } else {
            switch (data.status + '') {
              case '0':
                if (method !== 'get') {
                  // Toast.success(data.message);
                }
                if (data) {
                  resolve(data.data || {});
                } else {
                  // Toast.error('未查询到数据');
                  reject();
                }
                break;
              case '2':
                resolve(data || {});
                break;
              case 'NO_AUTH':
                // Toast.error('身份验证失败，请重新登录');
                // history.push('/user/login');
                break;
              case 'NO_PERMISSION':
                // Toast.error('没有相关权限，禁止操作');
                reject(data);
                break;
              case 'FAIL':
                // Toast.error(data.message);
                reject(data)
                break;
              default:
                break;
            }
          }
        } else {
          reject(data);
        }
      })
      .catch((error) => {
        reject(error);
      })
      .finally(() => {
        progressDone();
      });
  });
};

let fetchingToken = false;

const getToken = () => {
  const tokenData = localStorage.getItem('tokenData');
  return tokenData ? JSON.parse(tokenData) : {};
};

/* 请求服务器，刷新token */
const requestToken = () => {
  const tokenData = getToken();
  const token = tokenData.token;
  const refreshToken = tokenData.refreshToken;
  const phone = tokenData.phone;
  if (!token || !refreshToken || !phone) {
    return;
  }
  fetchingToken = true;
  return request({
    url: '/account/refreshToken',
    method: 'post',
    params: { token, refreshToken, phone },
  })
    .then(data => {
      const oldTokenData = { ...getToken(), ...data };
      localStorage.setItem('tokenData', JSON.stringify(oldTokenData));
      return data;
    })
    .finally(() => {
      fetchingToken = false;
    });
};

const refreshToken = () => {
  requestToken();
  setInterval(requestToken, 540000);
};

// refreshToken();

/* get请求 */
const get = (url, params, dir) => {
  return request({ url, params, dir });
};

const requestWithAuth = requestData => {
  const tokenData = getToken();
  const token = tokenData.token;
  const user = tokenData.user;
  // const phone = tokenData.phone;
  if (fetchingToken) {
    return new Promise((resolve, reject) => {
      reject();
    });
  }
  const headers = {};
  headers['Access-Token'] = token;
  headers['user'] = user;
  // headers.Username = phone;
  return request(requestData, headers);
};

request.get = get;
// request.requestWithAuth = requestWithAuth;

module.exports = request
